from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from django.contrib.auth.decorators import login_required
from . import models


def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect(profile)
        else:
            return render(request, 'user/login.html', {'error': '登录失败'})
    return render(request, 'user/login.html', {})


def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        re_password = request.POST.get('re-password')
        if password != re_password:
            return render(request, 'user/login.html', {'error': '两次密码不一致'})
        if User.objects.filter(username=username).exists():
            return render(request, 'user/login.html', {'error': '用户名已存在'})
        try:
            validate_password(password)
        except Exception as e:
            return render(request, 'user/login.html', {
                'error': '密码不符合要求:%s' % e})
        user = User.objects.create_user(username=username,
                                        password=password)
        login(request, user)
        return redirect(profile)
    return render(request, 'user/login.html', {
    })


@login_required
def profile(request):
    score = -1
    if request.GET.get('finish'):
        score = request.user.level_set.latest('id').score
    return render(request, 'user/profile.html', {'score': score})


def rank(request):
    tops = models.Player.objects.order_by('-hi_score')[:10]
    return render(request, 'user/rank.html', {'tops': tops})


def index_view(request):
    return redirect(profile)
